﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using FbKPI.Facade.Validator;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Transactions;


namespace FBKPI.ProcessRequest
{
    /// <summary>
    /// Summary description for KPIAssignDetailHandler
    /// </summary>
    public class KPIAssignDetailHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string method = context.Request.Params["action"];
            string msg = string.Empty;
            if (method == "InputAssignKPI")
                msg = this.SaveInputKPIAssign();
            else
                msg = this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = "OK";
            string action = HttpContext.Current.Request.QueryString["action"];
            int ID = Convert.ToInt16(HttpContext.Current.Request.QueryString["ID"]);
            bool isActive = Convert.ToBoolean(HttpContext.Current.Request.QueryString["isActive"]);
            bool weightEnable = Convert.ToBoolean(HttpContext.Current.Request.QueryString["weightEnable"]);
            bool uomEnable = Convert.ToBoolean(HttpContext.Current.Request.QueryString["uomEnable"]);
            int UOMID = HttpContext.Current.Request.QueryString["UOM"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["UOM"]);
            int UOMMaxID = HttpContext.Current.Request.QueryString["UOMMax"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["UOMMax"]);
            int UOMMinID = HttpContext.Current.Request.QueryString["UOMMin"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["UOMMin"]);
            int KPIID = HttpContext.Current.Request.QueryString["KPI"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["KPI"]);
            int KPIAssignID = HttpContext.Current.Request.QueryString["KPIAssign"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["KPIAssign"]);
            int EmployeeID = HttpContext.Current.Request.QueryString["Employee"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["Employee"]);
            int Weight = HttpContext.Current.Request.QueryString["Weight"] == string.Empty ? 0 : Convert.ToInt16(HttpContext.Current.Request.QueryString["Weight"]);
            string Polarization = HttpContext.Current.Request.QueryString["Polarization"];
            int ManualCalculation = HttpContext.Current.Request.QueryString["ManualCalculation"] == string.Empty ? 0 : Convert.ToInt32(HttpContext.Current.Request.QueryString["ManualCalculation"]);
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["CurrUser"]));

          

            KPIAssignDetailFacade df = new KPIAssignDetailFacade();
            KPIAssignDetail KPIs = df.GetKPIAssignDetailByID(ID);
            KPIAssignDetailValidator dv = new KPIAssignDetailValidator();

            int KpiID = 0;
            int Employee_ID = 0;
            if (action != "unsign")
            {
                if (KPIs == null)
                {
                    KPIs = new KPIAssignDetail();
                    KPIs.ID = ID;
                    KPIs.isActive = isActive;
                    KPIs.WeightEnableFlag = weightEnable;
                    KPIs.UoMEnableFlag = uomEnable;
                    KPIs.UoM = new UoMFacade().GetUoMByID(UOMID);
                    KPIs.UoMDetailMax = new UoMDetailFacade().GetUoMDetailByID(UOMMaxID);
                    KPIs.UoMDetailMin = new UoMDetailFacade().GetUoMDetailByID(UOMMinID);
                    KPIs.KPI = new KPIFacade().GetKPIByID(KPIID);
                    KPIs.KPIAssign = new KPIAssignFacade().GetKPIAssignByID(KPIAssignID);
                    KPIs.Employee = new EmployeeFacade().GetEmployeeByID(EmployeeID);
                    KPIs.Weight = Weight;
                    KPIs.Polarization = Polarization;
                    KPIs.ManualCalculation = ManualCalculation;
                    KPIs.CreateBy = CurrUser.Email;
                   
                    msg = dv.ValidateOnSave(KPIs);
                }
            }
            else if (action != "delete")
            {
                if (action == "unsign")
                {
                     KpiID = Convert.ToInt32(HttpContext.Current.Request.Params["KpiID"]);
                     Employee_ID = Convert.ToInt32(HttpContext.Current.Request.Params["EmployeeID"]);

                   
                }
                else
                {
                    KPIs.isActive = isActive;
                    KPIs.WeightEnableFlag = weightEnable;
                    KPIs.UoMEnableFlag = uomEnable;
                    KPIs.UoM = new UoMFacade().GetUoMByID(UOMID);
                    KPIs.UoMDetailMax = new UoMDetailFacade().GetUoMDetailByID(UOMMaxID);
                    KPIs.UoMDetailMin = new UoMDetailFacade().GetUoMDetailByID(UOMMinID);
                    KPIs.KPI = new KPIFacade().GetKPIByID(KPIID);
                    KPIs.KPIAssign = new KPIAssignFacade().GetKPIAssignByID(KPIAssignID);
                    KPIs.Employee = new EmployeeFacade().GetEmployeeByID(EmployeeID);
                    KPIs.Weight = Weight;
                    KPIs.Polarization = Polarization;
                    KPIs.ManualCalculation = ManualCalculation;
                    KPIs.LastModifiedBy = CurrUser.Email;
                    msg = dv.ValidateOnUpdate(KPIs);
                }
            }


            else if (action == "delete")
                KPIs.LastModifiedBy = CurrUser.Email;

            if (msg == "OK")
            {
                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    switch (action)
                    {
                        case "save":
                            msg = df.Save(KPIs);
                          break;
                        case "delete":
                            msg = df.Delete(KPIs);
                            break;
                        case "unsign":
                            KPIAssignDetail objDtl = new KPIAssignDetailFacade().GetKPIAssignDetailByID(KpiID);
                            if (objDtl != null)
                            {
                                if (!objDtl.Mandatory)
                                {
                                    bool privilage = new KPIAssignDetailFacade().BeforeUnSignKPI(objDtl.Employee.ID, CurrUser.ID);
                                    if (privilage)
                                    {
                                        msg = new KPIAssignDetailFacade().UnSignKPI(KpiID, Employee_ID);
                                    }
                                    else
                                        msg = "Anda tidak berhak unsign KPI tersebut !";
                                }
                                else
                                {
                                    if (CurrUser.ID == objDtl.AssignBy)
                                    {
                                        msg = new KPIAssignDetailFacade().UnSignKPIMandatory(KpiID, Employee_ID);
                                    }
                                    else
                                    msg = "Anda tidak berhak Unsign KPI status mandatory !";
                                }
                            }
                          
                            break;
                    }
                    trans.Complete();
                    trans.Dispose();
                }
            }

            return msg;
        }

        private string SaveInputKPIAssign()
        {
            string msg = "OK";
            sysLogFacade sysLogFacade = new sysLogFacade();
            sysLog objSysLog = new sysLog();
            Employee CurrUser = new Employee();
            try
            {

                //string action = HttpContext.Current.Request.QueryString["action"];
                int KpiID = Convert.ToInt16(HttpContext.Current.Request.QueryString["KpiID"]);
                string EmployeeID = HttpContext.Current.Request.QueryString["EmployeeID"];
                string Weight = HttpContext.Current.Request.QueryString["Weight"];
                string Mandatory = HttpContext.Current.Request.QueryString["Mandatory"];
                string WeightAssign = HttpContext.Current.Request.QueryString["WeightAssign"];
                CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["CurrUser"]));
                Employee AssignTo = null;
                if (EmployeeID.Trim().Length == 0)
                {
                    msg = "Please select employee to be assigned";
                    return msg;
                }
                else
                {
                    AssignTo = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(EmployeeID.Trim()));
                }

                if (AssignTo != null)
                {
                    string jumlahRow = new KPIAssignDetailFacade().BeforeAssignKPI(KpiID, AssignTo.ID);
                    if (Convert.ToInt16(jumlahRow) != 0)
                    {
                        msg = "Assign tidak berhasil, Employee  sudah pernah di Assign KPI tersebut !";
                        return msg;

                    }

                    if (AssignTo.isLock)
                    {
                        msg = "Assign tidak berhasil, status employee dalam keadaan ter lock !";
                        return msg;
                    }
                }

                KPIFacade df = new KPIFacade();
                KPI KPIs = df.GetKPIByID(KpiID);

                //WeightValidator wv = new WeightValidator();
                //msg = wv.ValidateWeight(CurrUser, ka, KPIs.Year);

                if (!KPIs.isLockWeight)
                {
                    if (KPIs.AssignWeight == "2")
                    {
                        if (Convert.ToInt32(WeightAssign) < Convert.ToInt32(Weight))
                        {
                            msg = "Nilai Weight Assign :" + WeightAssign + " harus lebih besar/sama dengan weight KPI :" + Weight + " !";
                            return msg;
                        }
                    }
                }

                KPIValidator KPIValidator = new KPIValidator();
                msg = KPIValidator.ValidateKPIParentAndChildAssignment(AssignTo, KPIs);

                if (msg == "OK")
                {
                    IList<KPIAssign> KPIAssigns = new KPIAssignFacade().GetAllKPIAssignsByKPIID(KpiID);
                    KPIAssign ka = null;
                    if (KPIAssigns == null)
                    {
                        ka = new KPIAssign()
                        {
                            ID = 0,
                            isActive = true,
                            KPI = KPIs,
                            Location = CurrUser.SubBranch.Location,
                            ManualCalculation = KPIs.ManualCalculation,
                            Polarization = KPIs.Polarization,
                            RGM = CurrUser.SubBranch.Location.RGM,
                            SubBranch = CurrUser.SubBranch,
                            UoM = KPIs.UoM,
                            UoMDetailMax = KPIs.UoMDetailMax,
                            UoMDetailMin = KPIs.UoMDetailMin,
                            UoMEnableFlag = KPIs.UoMEnableFlag,
                            Verifier = CurrUser,
                            Weight = Convert.ToInt32(WeightAssign),
                            WeightEnableFlag = KPIs.WeightEnableFlag,
                            CreateBy = CurrUser.Email
                        };
                    }


                    WeightValidator wv = new WeightValidator();
                    //msg = wv.ValidateWeight(CurrUser, Existing, KPIs.Year);
                    int WeightValidate = 0;
                    if (WeightAssign == "" || WeightAssign == "0")
                        WeightValidate = Convert.ToInt32(Weight);
                    else
                        WeightValidate = Convert.ToInt32(WeightAssign);

                    msg = wv.ValidateWeightDua(AssignTo, WeightValidate, KPIs.Year);


                    if (msg == "OK")
                    {
                        KPIAssign kasaved = new KPIAssignFacade().GetKPIAssignsByKPIID(KPIs.ID);//.Where(x=>x.isActive);//.Where(x => x.SubBranch.ID == CurrUser.SubBranch.ID && x.isActive && x.CreateBy == CurrUser.Email).FirstOrDefault();
                        
                        KPIAssignDetail kad = new KPIAssignDetail()
                        {
                            ID = 0,
                            CreateBy = CurrUser.Email,
                            Employee = AssignTo,
                            isActive = true,
                            //KPI = KPIs,
                            KPIAssign = kasaved,
                            ManualCalculation = KPIs.ManualCalculation,
                            Polarization = KPIs.Polarization,
                            UoM = KPIs.UoM,
                            UoMDetailMax = KPIs.UoMDetailMax,
                            UoMDetailMin = KPIs.UoMDetailMin,
                            UoMEnableFlag = KPIs.UoMEnableFlag,
                            Weight = WeightValidate,// KPIs.Weight,
                            WeightEnableFlag = KPIs.WeightEnableFlag,
                            Mandatory = Mandatory == "1" ? true : false,
                            AssignBy = CurrUser.ID,
                            LastModifiedBy = CurrUser.Email
                        };



                        KPIAssignDetailFacade kpiDtlFacade = new KPIAssignDetailFacade();
                        if (kpiDtlFacade.Save(ka, kad, AssignTo))
                        {

                            msg = "Transaction Success !";

                            //KPISendEmail objSendEmail = new KPISendEmail();
                            //objSendEmail.KPIEmail(kasaved.KPI.ID, CurrUser.FirstName, kad.Employee.ID);

                        }
                        else
                            msg = "Transaction Failed";
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                objSysLog.Description = ex.Message;
                objSysLog.LogEvent = "Input Assign Detail KPI";
                objSysLog.Source = "KPIAssignDetailHandler.ashx";
                objSysLog.CreatedBy = CurrUser.Email;
                objSysLog.CreatedDate = DateTime.Now;
                sysLogFacade.Save(objSysLog);
            }
            
            return msg;
        }
    }
}